<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<html>
	<head>
	<title>Insert title here</title>
	<script type="text/javascript">
		function getXHR(){//得到xhr
			//1.定义变量
			var xhr;
			
			//2.判断
			if(window.XMLHttpRequest){
				xhr = new XMLHttpRequest();
			}else{//ie5 ie6
				xhr = new ActiveXObject("Microsoft.XMLHttp"); 
			}
			return xhr;
			
		}
	
		function checkNameFun(){//name文本框失去焦点事件处理函数
			//1.创建xhr对象
			var xhr = getXHR();
			//2.监听事件,处理事件
			xhr.onreadystatechange=function(){
				//判断状态是第5种且状态码为200
				if(xhr.readyState==4 && xhr.status==200){
					console.log(xhr.responseText);
					var message = xhr.responseText;
					var node = document.getElementById("namespan");
					
					if(message=="0"){
						node.innerHTML = "用户名已被占用";
					}else{
						node.innerHTML = "用户名可以使用";
					}
				}
			};
			//3.打开连接
			var nameValue = document.getElementById("username").value;
			xhr.open("get","${pageContext.request.contextPath}/user/checkName.do?username="+ nameValue,true);
			
			//4.发送请求
			xhr.send();
		
		}
		
		function getCity(provinceCode){
			//1.定义变量
			var xhr = getXHR();
			//2.判断
			xhr.onreadystatechange = function(){
				if(xhr.readyState==4 && xhr.status==200){
					console.log(xhr.responseText);
					var cities = xhr.responseText;
					
					//获取city节点
					var node = document.getElementById("city");
					node.innerHTML = "<option>---请选择---</option>";
					if(cities != null){
						//拆分
						var city = cities.split(";");
						for(var i=0;i<city.length;i++){
							var cityShow = city[i].split(",");
							var cityCode = cityShow[0];
							var cityName = cityShow[1];
							//创建Option对象
							var op = new Option(cityName,cityCode);//城市名,城市代码  /*new Option(text,value)*/
							node.appendChild(op);
						}  
					}
				}
			}
			//3.打开连接
			xhr.open("post","${pageContext.request.contextPath}/user/getCity.do",true);
			xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");//在send之前设置一个请求头,值与form表单的enctype值一样
			//4.发送请求
			xhr.send("provinceCode="+provinceCode);
		}
		
		
	</script>
	</head>
	<body>
		<h1>AJAX的用户注册用户名验证(get)</h1>
		<form action="">
			用户姓名:<input type="text" name="username" id="username"  onblur="checkNameFun();"> <span id="namespan"></span><br>
			用户密码:<input type="password" name="password" id="password"><br>
			<input type="submit" value="提交">
		</form>
		
		<h1>AJAX的二级联动菜单(post)</h1>
			省:<select id="province" name="province" onchange="getCity(this.value);">
					<option>---请选择---</option>
					<option value="1">四川省</option>
					<option value="2">广东省</option>
				</select>
			城市:<select id="city" name="city">
					<option>---请选择---</option>
				</select>
	
	</body>
</html>